#include <stdio.h>
#include <string.h>
#include "driver/uart.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

# include "bsp_uart.h"

#include "dht.h"
#include "esp_timer.h"
#include "modbus_params.h"      // for modbus parameters structures
#include "mbcontroller.h"       // for mbcontroller defines and api


#include "oled.h"

#define TXD_GPIO_NUM 10 // 定义发送引脚 GPIO17
#define RXD_GPIO_NUM 9 // 定义接收引脚 GPIO16
static const char *TAG = "DHT11_MODBUS_SLAVE";
#define DHT_GPIO 11




void dht_task(void *pvParameters)
{
    float temperature, humidity;

    while (1) {
        if (dht_read_float_data(DHT_TYPE_DHT11, DHT_GPIO, &humidity, &temperature) == ESP_OK) {
            ESP_LOGI(TAG, "Temp: %.1f°C, Hum: %.1f%%", temperature, humidity);
            
       
//  OLED_ShowNum(u8 x,u8 y,u32 num,u8 len,u8 size1,u8 mode)
        OLED_ShowString(0,0,(unsigned char*)"Temp:",24,1);
        OLED_ShowNum(64,0,temperature,2,24,1);
        OLED_ShowChinese(92,5,11,16,1);//子

        OLED_ShowString(0,30,(unsigned char*)"Hum:",24,1);
        OLED_ShowNum(50,30,humidity,2,24,1);
       OLED_ShowString(78,30,(unsigned char*)"%",24,1);//6*8 “ABC”



                   
        OLED_Refresh();

            // 更新 Modbus 寄存器
            holding_reg_params.temperature = temperature;
            holding_reg_params.humidity = humidity;
        } else {
            ESP_LOGE(TAG, "Failed to read DHT11");
        }

        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}


void app_main(void) {



    OLED_Init();        //初始化OLED
    OLED_Clear(); //清屏

    uart_set_pin(UART_NUM_2, 10, 9, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE); // TX=17, RX=16

    
    void* handler = NULL;
    mb_communication_info_t comm_info = {
        .mode = MB_MODE_RTU,
        .slave_addr = 1,
        .port = UART_NUM_2,
        .baudrate = 115200,
        .parity = UART_PARITY_DISABLE
    };

    ESP_ERROR_CHECK(mbc_slave_init(MB_PORT_SERIAL_SLAVE, &handler));
    ESP_ERROR_CHECK(mbc_slave_setup((void*)&comm_info));

    
    // 设置寄存器描述符
    mb_register_area_descriptor_t reg_area = {
        .start_offset = 0x0000,
        .type = MB_PARAM_HOLDING,
        .address = &holding_reg_params,
        .size = sizeof(holding_reg_params)
    };
    ESP_ERROR_CHECK(mbc_slave_set_descriptor(reg_area));
    ESP_ERROR_CHECK(mbc_slave_start());
    xTaskCreate(dht_task, "dht_task", 4096, NULL, 5, NULL);
    ESP_LOGI(TAG, "Modbus slave started on UART2");

    



//     表格
// 复制
// 目标	原始帧（十六进制）
// 读取温度	01 03 00 00 00 02 C4 0B
// 读取湿度	01 03 00 02 00 02 65 CB



// from pymodbus.client.sync import ModbusSerialClient

// client = ModbusSerialClient(method='rtu', port='COM3', baudrate=9600, timeout=1)
// client.connect()

// # 读取温度
// result = client.read_holding_registers(0, 2, unit=1)
// temp_bytes = result.registers
// temperature = struct.unpack('<f', struct.pack('<HH', *temp_bytes))[0]

// # 读取湿度
// result = client.read_holding_registers(2, 2, unit=1)
// hum_bytes = result.registers
// humidity = struct.unpack('<f', struct.pack('<HH', *hum_bytes))[0]

// print(f"温度: {temperature}°C")
// print(f"湿度: {humidity}%")

}
